//
//  WKWebViewController.m
//  WebJs
//
//  Created by lizq on 16/9/5.
//  Copyright © 2016年 lizq. All rights reserved.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <JavaScriptCore/JavaScriptCore.h>

#import "NSString+URLParse.h"

@interface WKWebViewController () <WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ABPeoplePickerNavigationControllerDelegate>
@property(nonatomic,strong)WKWebView *webView;
@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
    // 加载
    NSString *path = [[NSBundle mainBundle] pathForResource:@"js" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url];
    [self.webView loadRequest:requst];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (WKWebView *)webView {
    if(!_webView) {
        // WKUserContentController
        WKUserContentController *userCC = [[WKUserContentController alloc] init];
        [userCC addScriptMessageHandler:self name:@"JsCallOc"];
        [userCC addScriptMessageHandler:self name:@"nomethodCall"];
        // WKUserScript 1
        NSString *js1 = [NSString stringWithFormat:@"\
                        function success(content) { \
                        var element = document.getElementById('p1'); \
                        element.innerHTML = content;\
                        } "];
        WKUserScript *script1 = [[WKUserScript alloc] initWithSource:js1 injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [userCC addUserScript:script1];
        // WKUserScript 1
        NSString *js2 = [NSString stringWithFormat:@"function action(operation) { \
                         var element = document.getElementById('p1'); \
                         element.innerHTML = operation; \
                         window.location.href = \"action::\" + operation;\
                         }"];
        WKUserScript *script2 = [[WKUserScript alloc] initWithSource:js2 injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [userCC addUserScript:script2];
        // WKWebViewConfiguration
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userCC;
        // WKWebView
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    return _webView;
}

#pragma mark ---
#pragma mark WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"\nname: %@\nbody:%@",message.name,message.body);

    NSString *name = [NSString stringWithFormat:@"%@:",message.name];
    SEL method = NSSelectorFromString(name);
    if([self respondsToSelector:method]) {
        [self performSelector:method withObject:message.body];
    }else {
        NSString *js = [NSString stringWithFormat:@"myfunction('no method %@')",message.name];
        [self.webView evaluateJavaScript:js completionHandler:^(id data, NSError * error) {
            NSLog(@"a error method received");
        }];
    }
}

- (void)JsCallOc:(id)body {
    NSLog(@"%@:%@",NSStringFromSelector(_cmd),body);
    
}

#pragma mark ---
#pragma mark navigation delegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"1");
    NSString *path = navigationAction.request.URL.absoluteString;
    NSLog(@"\n----- path : %@",path);
    if([path hasPrefix:@"app:"]) {
        NSArray *components = [path componentsSeparatedByString:@":"];
        NSString *request = [components objectAtIndex:1];
        NSDictionary *dic = [request urlParse];
        NSString *method =  dic[@"method"];
        SEL sel = NSSelectorFromString([NSString stringWithFormat:@"%@:",method]);
        if([self respondsToSelector:sel]) {
            [self performSelector:sel withObject:dic];
        }else {
            NSLog(@"no '%@' method",method);
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"3");
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"5");
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"6");
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"2");
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSLog(@"4");
    decisionHandler(WKNavigationResponsePolicyAllow);
}

#pragma mark ---
#pragma mark address book

- (void)requestContactList:(NSDictionary *)dic {
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 * cancel
 */
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self requestContactListCallBack:nil];
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}


/**
 * select person property
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    // person name
    ABMultiValueRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    ABMultiValueRef lastName =  ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *personName = [NSString stringWithFormat:@"%@%@",(__bridge NSString *)lastName,(__bridge NSString *)firstName];
    // person tel
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSDictionary *dic = @{@"contactName":personName,@"phoneNum":phoneNO};
    NSArray *list = @[dic];
    [self requestContactListCallBack:list];
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

/**
 * select person
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

/**
 * 调用通讯录回调
 */
- (void)requestContactListCallBack:(NSArray *)phoneList {
    if(phoneList && phoneList.count > 0) {
        // 成功
        NSDictionary *returnDic = @{@"resultCode":@"0000",
                              @"resultMessage":@"成功",
                              @"list":phoneList};
        NSString *string = [NSString stringWithFormat:@"%@",returnDic];
        NSString *js = [NSString stringWithFormat:@"success('%@')",string];
        [self.webView evaluateJavaScript:js completionHandler:^(id obj, NSError * error) {
            NSLog(@"联系写入成功");
        }];
    }else {
        // 成功
        NSDictionary *returnDic = @{@"resultCode":@"1111",
                                    @"resultMessage":@"失败",
                                    @"list":@[]};
        NSString *string = [NSString stringWithFormat:@"%@",returnDic];
        NSString *js = [NSString stringWithFormat:@"success('%@')",string];
        [self.webView evaluateJavaScript:js completionHandler:^(id obj, NSError * error) {
            NSLog(@"联系写入失败");
        }];
    }
}

#pragma mark ---
#pragma mark camera

- (void)requestPhoto:(NSDictionary *)dic {
    // 10-直接拍照 01-从相册中选 11-拍照或相册
    NSString *type = [dic objectForKey:@"type"];
    if([type isEqualToString:@"10"]) {
        [self openCamera:1];
    }else if([type isEqualToString:@"01"]) {
        [self openCamera:2];
    }else if([type isEqualToString:@"11"]) {
        UIAlertController *alert = [[UIAlertController alloc] init];
        alert.title = @"选择";
        [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            [self openCamera:1];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            [self openCamera:2];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *  action) {
            // 调用图片失败
            [self requestPhotoCallBack:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)openCamera:(NSInteger)type {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = type == 1?UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imageBase64 = [NSString stringWithFormat:@"%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
    // 获取图片成功
    [self requestPhotoCallBack:imageBase64];
}


/**
 * 调用图片回调
 */
- (void)requestPhotoCallBack:(NSString *)imageBase64 {
    if(imageBase64 == nil) {
        NSDictionary *returnDic = @{@"resultCode":@"1111",
                                    @"resultMessage":@"失败",
                                    @"image":@""};
        NSString *string = [NSString stringWithFormat:@"%@",returnDic];
        NSString *js = [NSString stringWithFormat:@"success('%@')",string];
        [self.webView evaluateJavaScript:js completionHandler:^(id obj, NSError * error) {
            NSLog(@"图片写入失败");
        }];
    }else {
        NSDictionary *returnDic = @{@"resultCode":@"0000",
                                    @"resultMessage":@"成功",
                                    @"image":imageBase64};
        NSString *resultValue = [[[NSString stringWithFormat:@"%@",returnDic] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        NSString *js = [NSString stringWithFormat:@"success('%@')",resultValue];
        [self.webView evaluateJavaScript:js completionHandler:^(id obj, NSError * error) {
            NSLog(@"图片写入成功");
        }];
    }
}

@end
